
#include "comClient.h"
#include "../comProtocol.h"

#include <stdio.h>
#include <string>
#include "winsock.h"

using namespace std;

ComClient::ComClient() {
}
// ----------
// Destruktor - provadi uklid po winsocks
ComClient::~ComClient() {
	WSACleanup();
}

// ----------
// Vytvori spojeni se serverem, ktery bezi na zadane ip adrese a na zadanem portu
int ComClient::Connect(string ip, int port) {
	// ----------
	// Inicializace Winsock
    WSADATA wsaData;
    int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
	if ( iResult != NO_ERROR ) {
        printf("Error: Inicializace WinSock se nezdarila\n");
		return 1;
	}
	
	// ----------
    // Vytvoreni socketu pro pripojeni k serveru
    serverConnection = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

    if ( serverConnection == INVALID_SOCKET ) {
        printf( "Error: Chyba pri vytvareni socketu (%ld)\n", WSAGetLastError() );
        return 1;
    }

	// ----------
    // Pripojeni k serveru
    sockaddr_in clientService;

    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( ip.c_str() );
    clientService.sin_port = htons( port );

    if ( connect( serverConnection, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) {
        printf( "Spojeni se serverem se nepodarilo navazat.\n" );
        return 1;
    }

	return 0;
}


// ----------
// Odesle zadana data na server
int ComClient::SendData(ComData data) {
	std::string xmlData = data.ToXML();
	int bytesSent = send( serverConnection, xmlData.c_str(), xmlData.size() +1, 0 );
	//int bytesSent = send( serverConnection, (char *)&data, sizeof(ComData), 0 );
	return bytesSent;
}
// ----------
// Prijima data ze serveru
int ComClient::RecieveData(ComData* data) {
	char buf[1024*16];
	  
	int bytesRecv = SOCKET_ERROR;

	while( bytesRecv == SOCKET_ERROR ) {
		bytesRecv = recv(this->serverConnection, buf, 1024*16, 0 );
    if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {
        printf( "Spojeni se serverem se nezdarilo.\n");
        break;
    }

		string xmlData = buf;
		data->FromXML(xmlData);
  }

	//int bytesRecv = SOCKET_ERROR;
/*
	while( bytesRecv == SOCKET_ERROR ) {
		bytesRecv = recv(this->serverConnection, (char*)data, sizeof(ComData), 0 );
    if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {
        printf( "Spojeni se serverem se nezdarilo.\n");
        break;
    }
*/
	return bytesRecv;
}